<template>
  <div class="knowledge-notes-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">知识点笔记</h1>
      <div class="header-actions">
        <el-button @click="createNewNote">
          <el-icon><Plus /></el-icon>
          创建笔记
        </el-button>
        <el-button @click="importNotes">
          <el-icon><Upload /></el-icon>
          导入笔记
        </el-button>
        <el-button @click="exportNotes">
          <el-icon><Download /></el-icon>
          导出笔记
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-filter-section">
      <el-card>
        <div class="search-filter-content">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索知识点或笔记内容..."
            prefix-icon="Search"
            class="search-input"
            @keyup.enter="searchNotes"
          />
          
          <el-select v-model="categoryFilter" placeholder="选择分类" class="filter-select">
            <el-option label="全部" value="all" />
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
          
          <el-select v-model="sortBy" placeholder="排序方式" class="filter-select">
            <el-option label="最近创建" value="createdAt" />
            <el-option label="最近修改" value="updatedAt" />
            <el-option label="标题排序" value="title" />
          </el-select>
          
          <el-button type="primary" @click="searchNotes">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </div>
      </el-card>
    </div>

    <!-- 知识点分类导航 -->
    <div class="category-navigation">
      <el-card class="category-card">
        <div class="category-header">
          <h2>知识点分类</h2>
          <el-button type="text" @click="manageCategories">
            <el-icon><Setting /></el-icon>
            管理分类
          </el-button>
        </div>
        
        <div class="category-list">
          <div
            v-for="category in categories"
            :key="category.id"
            :class="['category-item', { 'active': categoryFilter === category.id }]"
            @click="filterByCategory(category.id)"
          >
            <div class="category-info">
              <div class="category-name">{{ category.name }}</div>
              <div class="category-count">{{ getCategoryNoteCount(category.id) }} 篇笔记</div>
            </div>
            <div class="category-progress">
              <el-progress
                :percentage="category.completionRate"
                :stroke-width="6"
                :color="getCompletionColor(category.completionRate)"
                :show-text="false"
              />
              <div class="completion-text">{{ category.completionRate }}%</div>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 笔记列表 -->
    <div class="notes-list-section">
      <el-card class="notes-card">
        <div class="notes-header">
          <h2>我的笔记</h2>
          <div class="notes-stats">
            <span>共 {{ filteredNotes.length }} 篇笔记</span>
            <span v-if="searchKeyword">（搜索结果）</span>
          </div>
        </div>
        
        <div class="notes-content">
          <div v-if="filteredNotes.length === 0" class="no-notes">
            <el-empty description="暂无笔记" />
            <el-button type="primary" @click="createNewNote" class="create-first-note">
              <el-icon><Plus /></el-icon>
              创建第一篇笔记
            </el-button>
          </div>
          
          <div v-else class="notes-grid">
            <el-card
              v-for="note in paginatedNotes"
              :key="note.id"
              class="note-item"
              @click="viewNoteDetails(note.id)"
            >
              <div class="note-header">
                <h3 class="note-title">{{ note.title }}</h3>
                <div class="note-meta">
                  <el-tag size="small">{{ getCategoryName(note.categoryId) }}</el-tag>
                  <span class="note-date">{{ formatDate(note.updatedAt) }}</span>
                </div>
              </div>
              
              <div class="note-preview">
                {{ getNotePreview(note.content) }}
              </div>
              
              <div class="note-tags">
                <el-tag
                  v-for="tag in note.tags"
                  :key="tag"
                  size="small"
                  type="info"
                  :disable-transitions="true"
                >
                  {{ tag }}
                </el-tag>
              </div>
              
              <div class="note-actions">
                <el-button type="text" size="small" @click.stop="editNote(note.id)">
                  编辑
                </el-button>
                <el-button type="text" size="small" danger @click.stop="deleteNote(note.id)">
                  删除
                </el-button>
              </div>
            </el-card>
          </div>
        </div>
        
        <!-- 分页 -->
        <div v-if="filteredNotes.length > 0" class="notes-pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredNotes.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 创建/编辑笔记对话框 -->
    <el-dialog
      v-model="noteDialogVisible"
      :title="isEditing ? '编辑笔记' : '创建新笔记'"
      width="800px"
      :fullscreen="isFullscreen"
      :before-close="handleDialogClose"
    >
      <el-form :model="noteForm" :rules="noteFormRules" ref="noteFormRef" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="noteForm.title" placeholder="请输入笔记标题" />
        </el-form-item>
        
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="noteForm.categoryId" placeholder="请选择分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.name" :value="category.id" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="标签" prop="tags">
          <el-input
            v-model="noteForm.tagsText"
            placeholder="请输入标签，用逗号分隔"
            @change="handleTagsChange"
          />
          <div class="tags-preview">
            <el-tag
              v-for="tag in noteForm.tags"
              :key="tag"
              type="info"
              size="small"
              closable
              @close="removeTag(tag)"
            >
              {{ tag }}
            </el-tag>
          </div>
        </el-form-item>
        
        <el-form-item label="重要性" prop="importance">
          <el-rate v-model="noteForm.importance" :colors="['#909399', '#e6a23c', '#f56c6c']" show-score />
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <div class="editor-container">
            <div class="editor-toolbar">
              <el-button type="text" size="small" @click="insertFormat('bold')">
                <el-icon><Bold /></el-icon>
              </el-button>
              <el-button type="text" size="small" @click="insertFormat('italic')">
                <el-icon><Italic /></el-icon>
              </el-button>
              <el-button type="text" size="small" @click="insertFormat('underline')">
                <el-icon><Underline /></el-icon>
              </el-button>
              <el-divider direction="vertical" />
              <el-button type="text" size="small" @click="insertFormat('header', 1)">H1</el-button>
              <el-button type="text" size="small" @click="insertFormat('header', 2)">H2</el-button>
              <el-button type="text" size="small" @click="insertFormat('header', 3)">H3</el-button>
              <el-divider direction="vertical" />
              <el-button type="text" size="small" @click="insertFormat('list', 'ordered')">
                <el-icon><List /></el-icon>
              </el-button>
              <el-button type="text" size="small" @click="insertFormat('list', 'bullet')">
                <el-icon><Menu /></el-icon>
              </el-button>
              <el-divider direction="vertical" />
              <el-button type="text" size="small" @click="insertFormat('link')">
                <el-icon><Link /></el-icon>
              </el-button>
              <el-button type="text" size="small" @click="insertFormat('image')">
                <el-icon><Picture /></el-icon>
              </el-button>
              <el-button type="text" size="small" @click="insertFormat('code')">
                <el-icon><Code /></el-icon>
              </el-button>
            </div>
            <el-input
              v-model="noteForm.content"
              type="textarea"
              placeholder="请输入笔记内容，可以使用Markdown格式..."
              :autosize="{ minRows: 12, maxRows: 20 }"
              class="note-editor"
            />
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="toggleFullscreen">
            <el-icon>{{ isFullscreen ? 'MinusSquare' : 'PlusSquare' }}</el-icon>
            {{ isFullscreen ? '退出全屏' : '全屏编辑' }}
          </el-button>
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="saveNote">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 管理分类对话框 -->
    <el-dialog
      v-model="categoryDialogVisible"
      title="管理分类"
      width="600px"
    >
      <div class="category-management">
        <el-input
          v-model="newCategoryName"
          placeholder="输入新分类名称"
          class="add-category-input"
          @keyup.enter="addCategory"
        >
          <template #append>
            <el-button @click="addCategory">添加</el-button>
          </template>
        </el-input>
        
        <div class="category-list-management">
          <div
            v-for="category in categories"
            :key="category.id"
            class="category-item-management"
          >
            <div class="category-info-management">
              <span class="category-name-management">{{ category.name }}</span>
              <span class="category-count-management">({{ getCategoryNoteCount(category.id) }} 篇笔记)</span>
            </div>
            <div class="category-actions-management">
              <el-button type="text" size="small" @click="editCategory(category.id)">
                编辑
              </el-button>
              <el-button type="text" size="small" danger @click="deleteCategory(category.id)" :disabled="getCategoryNoteCount(category.id) > 0">
                删除
              </el-button>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus'
import {
  Plus,
  Upload,
  Download,
  Search,
  Setting,
  List,
  Menu,
  Link,
  Picture
} from '@element-plus/icons-vue'



// 响应式数据
const searchKeyword = ref('')
const categoryFilter = ref('all')
const sortBy = ref('updatedAt')
const currentPage = ref(1)
const pageSize = ref(10)
const noteDialogVisible = ref(false)
const categoryDialogVisible = ref(false)
const isEditing = ref(false)
const isFullscreen = ref(false)
const newCategoryName = ref('')
const editingCategoryId = ref<string | null>(null)
const noteFormRef = ref<FormInstance>()

// 笔记表单数据
const noteForm = reactive({
  id: '',
  title: '',
  categoryId: '',
  tags: [] as string[],
  tagsText: '',
  content: '',
  importance: 1,
  createdAt: new Date(),
  updatedAt: new Date()
})

// 笔记表单验证规则
const noteFormRules: FormRules = {
  title: [
    { required: true, message: '请输入笔记标题', trigger: 'blur' },
    { min: 1, max: 100, message: '标题长度应在1-100个字符之间', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入笔记内容', trigger: 'blur' },
    { min: 1, message: '内容不能为空', trigger: 'blur' }
  ]
}

// 分类数据
const categories = ref([
  { id: '1', name: '图形推理', completionRate: 75 },
  { id: '2', name: '定义判断', completionRate: 80 },
  { id: '3', name: '类比推理', completionRate: 90 },
  { id: '4', name: '逻辑判断', completionRate: 70 },
  { id: '5', name: '言语理解', completionRate: 65 },
  { id: '6', name: '数量关系', completionRate: 50 },
  { id: '7', name: '资料分析', completionRate: 85 }
])

// 笔记数据
const notes = ref([
  {
    id: '1',
    title: '图形推理之位置类规律总结',
    categoryId: '1',
    tags: ['图形推理', '位置类', '平移', '旋转', '翻转'],
    content: '# 图形推理之位置类规律总结\n\n## 一、位置类图形推理概述\n位置类图形推理是判断推理考试中的常见题型，主要考察图形元素的位置变化规律。\n\n## 二、常见位置变化规律\n\n### 1. 平移\n平移是指图形元素在平面内按照一定方向和距离进行移动。\n- **方向**：水平、垂直、对角线、顺时针、逆时针\n- **距离**：恒定距离、递增距离、递减距离\n\n### 2. 旋转\n旋转是指图形元素围绕某一点按照一定方向和角度进行转动。\n- **方向**：顺时针、逆时针\n- **角度**：常见的有45°、90°、180°等\n\n### 3. 翻转\n翻转是指图形元素沿某一直线进行翻转，得到镜像图形。\n- **横轴翻转**：上下翻转\n- **纵轴翻转**：左右翻转\n\n## 三、解题技巧\n1. 观察图形元素是否相同\n2. 确定位置变化的类型（平移、旋转、翻转）\n3. 找出位置变化的规律（方向、距离、角度等）\n4. 验证规律并应用到所求图形',
    importance: 5,
    createdAt: new Date('2024-05-20T10:00:00'),
    updatedAt: new Date('2024-05-21T15:30:00')
  },
  {
    id: '2',
    title: '逻辑判断之翻译推理知识点',
    categoryId: '4',
    tags: ['逻辑判断', '翻译推理', '必然性推理'],
    content: '# 逻辑判断之翻译推理知识点\n\n## 一、翻译规则\n\n### 1. 充分条件（如果...那么...）\n如果A，那么B → A → B（前推后）\n常见逻辑联结词：如果...那么...、只要...就...、若...则...、所有...都...、凡是...都...\n\n### 2. 必要条件（只有...才...）\n只有A，才B → B → A（后推前）\n常见逻辑联结词：只有...才...、不...不...、除非...否则不...、A是B的必要条件\n\n### 3. 逆否命题\n原命题：A → B\n逆否命题：¬B → ¬A\n原命题与逆否命题等价\n\n## 二、推理规则\n\n### 1. 递推规则\n如果A → B，且B → C，则A → C\n\n### 2. 逆否等价\nA → B 等价于 ¬B → ¬A\n\n### 3. 摩根定律\n¬(A ∧ B) = ¬A ∨ ¬B\n¬(A ∨ B) = ¬A ∧ ¬B\n\n## 三、解题步骤\n1. 翻译：将题干中的逻辑语句翻译成逻辑表达式\n2. 推理：根据推理规则进行逻辑推理\n3. 验证：验证选项是否符合推理结果',
    importance: 5,
    createdAt: new Date('2024-05-18T09:15:00'),
    updatedAt: new Date('2024-05-19T14:20:00')
  },
  {
    id: '3',
    title: '数量关系之工程问题公式总结',
    categoryId: '6',
    tags: ['数量关系', '工程问题', '公式'],
    content: '# 数量关系之工程问题公式总结\n\n## 一、基本公式\n工作总量 = 工作效率 × 工作时间\n工作效率 = 工作总量 ÷ 工作时间\n工作时间 = 工作总量 ÷ 工作效率\n\n## 二、常用解题方法\n\n### 1. 赋值法\n- 当题干中只给出工作时间时，通常赋值工作总量为时间的公倍数\n- 当题干中给出效率比时，通常赋值效率为对应的比例数\n\n### 2. 方程法\n设未知数，根据工作总量、工作效率、工作时间的关系列方程求解\n\n## 三、常见题型\n\n### 1. 基本工程问题\n例：一项工程，甲单独做需要10天完成，乙单独做需要15天完成，两人合作需要多少天完成？\n\n### 2. 多人合作问题\n- 总效率 = 各部分效率之和\n- 注意合作过程中的效率变化（如休息、交替工作等）\n\n### 3. 进水排水问题\n- 进水量 = 进水效率 × 进水时间\n- 排水量 = 排水效率 × 排水时间\n- 净水量 = 进水量 - 排水量\n\n## 四、典型例题解析\n（例题及解析内容略）',
    importance: 4,
    createdAt: new Date('2024-05-15T11:30:00'),
    updatedAt: new Date('2024-05-16T16:45:00')
  },
  {
    id: '4',
    title: '言语理解之逻辑填空解题技巧',
    categoryId: '5',
    tags: ['言语理解', '逻辑填空', '解题技巧'],
    content: '# 言语理解之逻辑填空解题技巧\n\n## 一、解题思路\n1. 分析上下文逻辑关系\n2. 辨析选项词语差异\n3. 选择最符合语境的词语\n\n## 二、逻辑关系分析\n\n### 1. 解释关系\n上下文之间存在解释说明的关系，通过解释内容可以确定空格处的词语\n\n### 2. 反对关系\n上下文之间存在相反或相对的关系，需要选择与呼应点相反的词语\n\n### 3. 递进关系\n上下文之间存在程度上的递进，需要选择语义更重或更轻的词语\n\n### 4. 联合关系\n上下文之间存在并列、选择、顺承等关系，需要选择与呼应点相近或相关的词语\n\n## 三、词语辨析角度\n\n### 1. 语义轻重\n有些词语语义较轻，有些词语语义较重，需要根据语境选择合适的词语\n\n### 2. 感情色彩\n词语的感情色彩包括褒义、贬义、中性，需要根据语境选择与作者态度一致的词语\n\n### 3. 词语搭配\n不同的词语有不同的搭配对象和习惯，需要注意词语的搭配是否恰当\n\n## 四、高频易错成语积累\n（成语列表及辨析内容略）',
    importance: 3,
    createdAt: new Date('2024-05-10T08:45:00'),
    updatedAt: new Date('2024-05-12T13:20:00')
  },
  {
    id: '5',
    title: '资料分析之速算技巧大全',
    categoryId: '7',
    tags: ['资料分析', '速算技巧', '估算'],
    content: '# 资料分析之速算技巧大全\n\n## 一、基础速算技巧\n\n### 1. 估算法\n- 四舍五入法：将数字近似为整十、整百、整千的数\n- 数位截取法：截取有效数字进行计算\n\n### 2. 直除法\n当除数的首位是1或2时，可直接进行除法运算，快速得到结果\n\n### 3. 插值法\n在计算两个数的比值时，插入中间值进行比较和计算\n\n## 二、进阶速算技巧\n\n### 1. 差分法\n比较两个分数大小时，通过比较差分数与小分数的大小来确定原分数的大小\n\n### 2. 化同法\n将两个分数的分子或分母化为相同或相近的数，再进行比较\n\n### 3. 增长率相关速算\n- 复合增长率：(1+r1)(1+r2)-1 ≈ r1+r2+r1×r2（当r1和r2较小时）\n- 基期量计算：现期量/(1+r) ≈ 现期量×(1-r)（当r较小时）\n\n## 三、常见题型速算\n\n### 1. 比重计算\n- 现期比重 = 部分量/总量\n- 基期比重 = (部分量/总量)×[(1+总量增长率)/(1+部分量增长率)]\n\n### 2. 增长量计算\n增长量 = 现期量 - 基期量 = 现期量×r/(1+r)\n\n## 四、速算练习建议\n（练习方法及注意事项略）',
    importance: 5,
    createdAt: new Date('2024-05-05T14:00:00'),
    updatedAt: new Date('2024-05-08T10:15:00')
  }
])

// 计算属性：过滤和排序后的笔记列表
const filteredNotes = computed(() => {
  let filtered = [...notes.value]
  
  // 根据关键词搜索
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase()
    filtered = filtered.filter(note => 
      note.title.toLowerCase().includes(keyword) ||
      note.content.toLowerCase().includes(keyword) ||
      note.tags.some(tag => tag.toLowerCase().includes(keyword))
    )
  }
  
  // 根据分类筛选
  if (categoryFilter.value !== 'all') {
    filtered = filtered.filter(note => note.categoryId === categoryFilter.value)
  }
  
  // 根据排序方式排序
  filtered.sort((a, b) => {
    if (sortBy.value === 'createdAt') {
      return b.createdAt.getTime() - a.createdAt.getTime()
    } else if (sortBy.value === 'updatedAt') {
      return b.updatedAt.getTime() - a.updatedAt.getTime()
    } else if (sortBy.value === 'title') {
      return a.title.localeCompare(b.title)
    }
    return 0
  })
  
  return filtered
})

// 分页后的笔记列表
const paginatedNotes = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return filteredNotes.value.slice(startIndex, endIndex)
})

// 获取分类名称
const getCategoryName = (categoryId: string) => {
  const category = categories.value.find(c => c.id === categoryId)
  return category ? category.name : '未分类'
}

// 获取分类笔记数量
const getCategoryNoteCount = (categoryId: string) => {
  return notes.value.filter(note => note.categoryId === categoryId).length
}

// 获取完成度颜色
const getCompletionColor = (rate: number) => {
  if (rate >= 90) return '#67c23a'
  if (rate >= 70) return '#e6a23c'
  if (rate >= 60) return '#f56c6c'
  return '#ff4949'
}

// 格式化日期
const formatDate = (date: Date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 获取笔记预览
const getNotePreview = (content: string) => {
  // 移除Markdown标记
  const plainText = content.replace(/#+\s+|\*\*|\*|`|\n/g, '')
  // 截取前100个字符
  return plainText.length > 100 ? plainText.substring(0, 100) + '...' : plainText
}

// 搜索笔记
const searchNotes = () => {
  currentPage.value = 1
}

// 按分类筛选
const filterByCategory = (categoryId: string) => {
  categoryFilter.value = categoryId
  currentPage.value = 1
}

// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

// 处理当前页码变化
const handleCurrentChange = (current: number) => {
  currentPage.value = current
}

// 创建新笔记
const createNewNote = () => {
  isEditing.value = false
  noteForm.id = ''
  noteForm.title = ''
  noteForm.categoryId = ''
  noteForm.tags = []
  noteForm.tagsText = ''
  noteForm.content = ''
  noteForm.importance = 1
  noteDialogVisible.value = true
}

// 编辑笔记
const editNote = (id: string) => {
  const note = notes.value.find(n => n.id === id)
  if (note) {
    isEditing.value = true
    noteForm.id = note.id
    noteForm.title = note.title
    noteForm.categoryId = note.categoryId
    noteForm.tags = [...note.tags]
    noteForm.tagsText = note.tags.join(', ')
    noteForm.content = note.content
    noteForm.importance = note.importance
    noteDialogVisible.value = true
  }
}

// 查看笔记详情
const viewNoteDetails = (id: string) => {
  // 在实际应用中，这里应该跳转到笔记详情页面
  // 这里简化处理，直接调用编辑功能
  editNote(id)
}

// 删除笔记
const deleteNote = async (id: string) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这篇笔记吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = notes.value.findIndex(n => n.id === id)
    if (index > -1) {
      notes.value.splice(index, 1)
    }
    
    // 如果当前页没有数据了，返回上一页
    if (paginatedNotes.value.length === 0 && currentPage.value > 1) {
      currentPage.value -= 1
    }
    
    ElMessage.success('笔记已删除')
  } catch (error) {
    // 用户取消操作
  }
}

// 保存笔记
const saveNote = async () => {
  if (!noteFormRef.value) return
  
  try {
    await noteFormRef.value.validate()
    
    const now = new Date()
    
    if (isEditing.value) {
      // 编辑现有笔记
      const index = notes.value.findIndex(n => n.id === noteForm.id)
      if (index > -1) {
        notes.value[index] = {
          ...notes.value[index],
          title: noteForm.title,
          categoryId: noteForm.categoryId,
          tags: noteForm.tags,
          content: noteForm.content,
          importance: noteForm.importance,
          updatedAt: now
        }
      }
      ElMessage.success('笔记已更新')
    } else {
      // 创建新笔记
      const newNote = {
        id: `note-${Date.now()}`,
        title: noteForm.title,
        categoryId: noteForm.categoryId,
        tags: noteForm.tags,
        content: noteForm.content,
        importance: noteForm.importance,
        createdAt: now,
        updatedAt: now
      }
      notes.value.unshift(newNote)
      ElMessage.success('笔记已创建')
    }
    
    // 关闭对话框
    noteDialogVisible.value = false
    
    // 如果有筛选条件，确保新笔记能显示在当前页
    if (categoryFilter.value !== 'all' && noteForm.categoryId === categoryFilter.value) {
      currentPage.value = 1
    }
  } catch (error) {
    // 验证失败或保存出错
  }
}

// 处理标签变化
const handleTagsChange = () => {
  if (noteForm.tagsText) {
    noteForm.tags = noteForm.tagsText.split(',').map(tag => tag.trim()).filter(tag => tag)
  } else {
    noteForm.tags = []
  }
}

// 移除标签
const removeTag = (tag: string) => {
  const index = noteForm.tags.indexOf(tag)
  if (index > -1) {
    noteForm.tags.splice(index, 1)
    noteForm.tagsText = noteForm.tags.join(', ')
  }
}

// 插入格式（简化版）
const insertFormat = (_formatType: string, _formatValue?: any) => {
  // 这里只是模拟插入格式，实际应用中应该获取光标位置并插入相应的Markdown标记
  ElMessage.info('格式插入功能待实现')
}

// 切换全屏
const toggleFullscreen = () => {
  isFullscreen.value = !isFullscreen.value
}

// 处理对话框关闭
const handleDialogClose = () => {
  if (noteForm.title || noteForm.content) {
    ElMessageBox.confirm(
      '确定要放弃当前编辑吗？',
      '确认放弃',
      {
        confirmButtonText: '确定',
        cancelButtonText: '继续编辑',
        type: 'warning'
      }
    ).then(() => {
      noteDialogVisible.value = false
    }).catch(() => {
      // 用户选择继续编辑
    })
  } else {
    noteDialogVisible.value = false
  }
}

// 管理分类
const manageCategories = () => {
  newCategoryName.value = ''
  editingCategoryId.value = null
  categoryDialogVisible.value = true
}

// 添加分类
const addCategory = () => {
  if (!newCategoryName.value.trim()) {
    ElMessage.error('请输入分类名称')
    return
  }
  
  // 检查分类名称是否已存在
  if (categories.value.some(c => c.name === newCategoryName.value.trim())) {
    ElMessage.error('分类名称已存在')
    return
  }
  
  // 如果正在编辑分类，则更新分类名称
  if (editingCategoryId.value) {
    const index = categories.value.findIndex(c => c.id === editingCategoryId.value)
    if (index > -1) {
      categories.value[index].name = newCategoryName.value.trim()
    }
    ElMessage.success('分类已更新')
    editingCategoryId.value = null
  } else {
    // 添加新分类
    const newCategory = {
      id: `category-${Date.now()}`,
      name: newCategoryName.value.trim(),
      completionRate: 0
    }
    categories.value.push(newCategory)
    ElMessage.success('分类已添加')
  }
  
  newCategoryName.value = ''
}

// 编辑分类
const editCategory = (id: string) => {
  const category = categories.value.find(c => c.id === id)
  if (category) {
    newCategoryName.value = category.name
    editingCategoryId.value = id
  }
}

// 删除分类
const deleteCategory = async (id: string) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个分类吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = categories.value.findIndex(c => c.id === id)
    if (index > -1) {
      categories.value.splice(index, 1)
    }
    
    // 如果当前筛选的是被删除的分类，切换到全部
    if (categoryFilter.value === id) {
      categoryFilter.value = 'all'
    }
    
    ElMessage.success('分类已删除')
  } catch (error) {
    // 用户取消操作
  }
}

// 导入笔记
const importNotes = () => {
  ElMessage.success('导入笔记功能待实现')
}

// 导出笔记
const exportNotes = () => {
  ElMessage.success('导出笔记功能待实现')
}

// 组件挂载时初始化
onMounted(() => {
  // 可以在这里加载用户的笔记数据
})
</script>

<style lang="scss" scoped>
.knowledge-notes-view {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  flex-wrap: wrap;
  gap: 15px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.search-filter-section {
  margin-bottom: 30px;
}

.search-filter-content {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
  padding: 20px;
}

.search-input {
  flex: 1;
  min-width: 300px;
}

.filter-select {
  width: 150px;
}

.category-navigation {
  margin-bottom: 30px;
}

.category-card {
  border-radius: 12px;
  overflow: hidden;
}

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.category-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.category-list {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  &:hover {
    border-color: #409eff;
    background-color: #ecf5ff;
  }
  &.active {
    border-color: #409eff;
    background-color: #ecf5ff;
  }
}

.category-info {
  flex: 1;
}

.category-name {
  font-size: 16px;
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 5px;
}

.category-count {
  font-size: 14px;
  color: #6b7280;
}

.category-progress {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 150px;
}

.completion-text {
  font-size: 12px;
  color: #6b7280;
  min-width: 40px;
  text-align: right;
}

.notes-list-section {
  margin-bottom: 30px;
}

.notes-card {
  border-radius: 12px;
  overflow: hidden;
}

.notes-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e5e7eb;
}

.notes-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #1f2937;
  margin: 0;
}

.notes-stats {
  font-size: 14px;
  color: #6b7280;
}

.notes-content {
  padding: 20px;
}

.no-notes {
  text-align: center;
  padding: 60px 20px;
}

.create-first-note {
  margin-top: 20px;
}

.notes-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.note-item {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  height: 100%;
  display: flex;
  flex-direction: column;
  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transform: translateY(-2px);
  }
}

.note-header {
  padding: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.note-title {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 10px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.note-meta {
  display: flex;
  align-items: center;
  gap: 10px;
}

.note-date {
  font-size: 12px;
  color: #6b7280;
}

.note-preview {
  padding: 15px;
  font-size: 14px;
  line-height: 1.6;
  color: #4b5563;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 4;
  -webkit-box-orient: vertical;
}

.note-tags {
  padding: 0 15px 15px 15px;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.note-actions {
  padding: 15px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.notes-pagination {
  padding: 20px;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #e5e7eb;
}

.editor-container {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.editor-toolbar {
  background-color: #f5f7fa;
  border-bottom: 1px solid #dcdfe6;
  padding: 8px 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.note-editor {
  border: none;
  resize: vertical;
  font-family: inherit;
}

.tags-preview {
  margin-top: 10px;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.category-management {
  padding: 20px 0;
}

.add-category-input {
  margin-bottom: 20px;
}

.category-list-management {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.category-item-management {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
}

.category-info-management {
  display: flex;
  align-items: center;
  gap: 10px;
}

.category-name-management {
  font-size: 16px;
  color: #1f2937;
}

.category-count-management {
  font-size: 14px;
  color: #6b7280;
}

.category-actions-management {
  display: flex;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .notes-grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .search-filter-content {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .filter-select {
    width: 100%;
  }
  
  .category-item {
    flex-direction: column;
    align-items: stretch;
    gap: 10px;
  }
  
  .category-progress {
    width: 100%;
  }
  
  .notes-grid {
    grid-template-columns: 1fr;
  }
  
  .editor-toolbar {
    flex-wrap: wrap;
  }
}
</style>